<?php

namespace App\Http\Controllers\Admin;

use App\Facades\EasyWechat;
use App\Services\WxMp\WxMpListService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;

/**
 * 公众平台授权控制器
 * @package App\Http\Controllers\Admin
 */
class WxMpOpenAuthorizerController extends BaseOpenController
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 首页
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        $curWxMp = $request->user()->getWxMpCurrent();
        $mpList = \App\Models\WxMpList::with('openAuthorizer')->where('open_appid', $curWxMp['appid'])->where('is_from_open', 1)->get();
        $this->viewData['mpList'] = $mpList;
        return view('admin.wxmpopenauthorizer.index', $this->viewData);
    }

    /**
     * 跳转开放平台授权链接
     */
    public function redirectAuthorized(Request $request)
    {
        if ($request->user()->cannot('admin.wxmpopenauthorizer.redirectauthorized')) {
            return $this->showMsg('error', '您暂无微信接入权限');
        }
        $curWxMp = $request->user()->getWxMpCurrent();
        //验证当前应用是否为同一平台
        $wxMpListSer = new WxMpListService();
        $curWxMpData = $wxMpListSer->getValidMpByAppid($curWxMp['appid']);
        if ($curWxMpData['type'] != WxMpListService::TYPE_OPEN_PLATFORM) {
            return $this->showMsg('error', '请选择微信开放平台应用', [], 'admin.index.index');
        }
        if ($curWxMpData['is_enable'] != 1) {
            return $this->showMsg('error', '该微信开放平台应用已停用', [], 'admin.index.index');
        }

        $openPlatform = EasyWechat::openPlatform($curWxMp['appid']);
        $preAuthorizationUrl = $openPlatform->getPreAuthorizationUrl(route('admin.wxmpopenauthorizer.redirectauthorizedcallback', ['appid' => $curWxMp['appid']]));
        return redirect($preAuthorizationUrl);
    }

    /**
     * 开放平台授权回跳页面
     */
    public function redirectAuthorizedCallback(Request $request)
    {
        if ($request->user()->cannot('admin.wxmpopenauthorizer.redirectauthorized')) {
            return $this->showMsg('error', '您暂无微信接入权限');
        }
        $curOpenAppId = $request->appid ?? '';
        //验证当前应用是否为同一平台
        $wxMpListSer = new WxMpListService();
        $curWxMpData = $wxMpListSer->getValidMpByAppid($curOpenAppId);
        if ($curWxMpData['type'] != WxMpListService::TYPE_OPEN_PLATFORM) {
            return $this->showMsg('error', '请选择微信开放平台应用', [], 'admin.index.index');
        }
        if ($curWxMpData['is_enable'] != 1) {
            return $this->showMsg('error', '该微信开放平台应用已停用', [], 'admin.index.index');
        }

        $openPlatform = EasyWechat::openPlatform($curOpenAppId);
        $res = $openPlatform->handleAuthorize($authCode = null);

        $appid = $res['authorization_info']['authorizer_appid'];
        $refresh_token = $res['authorization_info']['authorizer_refresh_token'];

        $authorizerInfo = $openPlatform->getAuthorizer($appid);
        //保存授权信息
        (new \App\Services\WxMp\WxMpListService($curOpenAppId))->openAuthorizerSave($authorizerInfo);

        sleep(1);
        $mp = \App\Models\WxMpList::where('appid', $appid)->first();
        $on = 0;
        if (empty($mp->refresh_token)) {
            $on = 1;
        }

        $this->viewData['on'] = $on;
        return view('admin.wxmpopenauthorizer.authorizedcallback', $this->viewData);
    }
}
